package com.ele.client.home;

import com.ele.client.Presenter;
import com.ele.client.rpc.ApplicationServiceAsync;
import com.ele.client.rpc.SimpleAsyncCallback;
import com.ele.client.util.PathHelper;
import com.ele.model.Question;
import com.ele.model.Section;
import com.ele.model.Word;
import com.github.gwtbootstrap.client.ui.*;
import com.github.gwtbootstrap.client.ui.constants.AlertType;
import com.google.gwt.dom.client.Style;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Widget;

public class HomePresenter implements Presenter {

    public interface Display {
        Widget asWidget();

        PageHeader getPageHeader();

        FlowPanel getWordsPanel();

        ControlLabel getQuestionLabel();

        TextBox getAnswerTextBox();

        Button getButton();

        ControlGroup getControlGroup();

        HelpBlock getHelpBlock();

        Image getImage();
    }

    private final ApplicationServiceAsync rpcService;
    private final HandlerManager eventBus;
    private final Display display;

    private Section currentSection;
    private Question currentQuestion;

    public HomePresenter(ApplicationServiceAsync rpcService, HandlerManager eventBus, Display display) {
        this.rpcService = rpcService;
        this.eventBus = eventBus;
        this.display = display;
    }

    public void bind() {
        display.getAnswerTextBox().addKeyDownHandler(new KeyDownHandler() {
            @Override
            public void onKeyDown(KeyDownEvent event) {
                if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
                    checkAnswer();
                }

                if (display.getAnswerTextBox().getValue().isEmpty()) {
                    display.getButton().setText("Не знаю (Enter)");
                } else {
                    display.getButton().setText("Проверить (Enter)");
                }
            }
        });

        display.getButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                checkAnswer();
            }
        });
    }

    private void checkAnswer() {
//        String answer = display.getAnswerTextBox().getValue();
//
//        if (QuestionHelper.isCorrectAnswer(currentQuestion, answer)) {
//            if (!currentQuestion.isWrongAnswered() || currentQuestion.getCount() >= 3) {
//                currentQuestion.setCompleted(true);
//            }
//
//            currentQuestion.setCount(currentQuestion.getCount() + 1);
//
//            List<Question> uncompletedQuestions = currentSection.getUncompletedQuestions();
//
//            if (uncompletedQuestions.isEmpty()) {
//                PathHelper.setId(PathHelper.getId() + 1);
//                loadData();
//            } else {
//                setQuestion(QuestionHelper.nextRndQuestion(currentSection));
//            }
//
//            display.getControlGroup().setType(ControlGroupType.NONE);
//            display.getHelpBlock().getElement().setInnerHTML("");
//        } else {
//            currentQuestion.setCount(0);
//            currentQuestion.setWrongAnswered(true);
//
//            display.getControlGroup().setType(ControlGroupType.ERROR);
//            StringBuilder sb = new StringBuilder("Правильный ответ:");
//            for (Answer a : currentQuestion.getAnswers()) {
//                sb.append("<br />").append(a.getText());
//            }
//            display.getHelpBlock().getElement().setInnerHTML(sb.toString());
//        }
    }

    public void go(final HasWidgets container) {
        bind();
        container.clear();
        container.add(display.asWidget());

        loadData();
    }

    private void loadData() {
        Long id = PathHelper.getId();

        rpcService.getSection(id, new SimpleAsyncCallback<Section>() {
            @Override
            public void onSuccess(Section section) {
//                if (section == null) {
//                    Window.alert("Section not found");
//                }
//
//                currentSection = section;
//
//                display.getPageHeader().setText(section.getName());
//
//                display.getWordsPanel().clear();
//                for (Word word : section.getWords()) {
//                    addWordControl(word);
//                }
//
//                setQuestion(QuestionHelper.nextRndQuestion(currentSection));
            }
        });
    }

    private void setQuestion(Question question) {
        currentQuestion = question;

        display.getQuestionLabel().getElement().setInnerText(question.getText());
        display.getImage().setVisible(question.getImgUrl() != null);
        display.getImage().setUrl(question.getImgUrl());
    }

    private void addWordControl(Word word) {
        final AlertBlock block = new AlertBlock(word.getTranslation());
        block.setHeading(word.getText());
        block.setClose(false);
        block.setType(AlertType.INFO);
        block.getElement().getStyle().setFloat(Style.Float.LEFT);
        block.getElement().getStyle().setMarginRight(5, Style.Unit.PX);
        block.setWidth("120px");

        display.getWordsPanel().add(block);
    }
}
